﻿#region directives

using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Linq;

#endregion

namespace ToodleDo.Client
{
    public static class Connection
    {
        #region Members

        public static bool Proxy { get; set; }
        public static string ProxyServer { get; set; }
        public static int ProxyPort { get; set; }
        public static string ProxyUsername { get; set; }
        public static string ProxyPassword { get; set; }

        #endregion

        #region Constructors & Init

        #endregion

        #region Public Methods

        public static XDocument Post(string url, string package)
        {
            WebRequest request = GetWebRequest(url);
            request.Method = "POST";
            byte[] byteArray = Encoding.UTF8.GetBytes(package);
            Debug.WriteLine(byteArray.ToString());
            request.ContentLength = byteArray.Length;
            request.ContentType = "application/x-www-form-urlencoded";
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse response = request.GetResponse();
            dataStream = response.GetResponseStream();

            //string data = "";
            //using (StreamReader sr = new StreamReader(dataStream,
            //Encoding.GetEncoding("ISO-8859-1")))
            //{
            //    data = sr.ReadToEnd();
            //}
            //todo test the proxy server
            //todo make it work, and test automatically for proxy
            return XDocument.Load(dataStream);
        }

        public static XDocument Get(string url)
        {
            WebRequest request = GetWebRequest(url);
            request.Method = "GET";
            WebResponse response = request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            return XDocument.Load(dataStream);
            //return XDocument.Load(url);
        }

        #endregion

        #region #Events & Invokables

        #endregion

        #region Private Methods

        private static WebRequest GetWebRequest(string url)
        {
            WebRequest request = WebRequest.Create(url);
            if (Proxy)
            {
                Logger.InvokeMessageEvent("Proxy engaged", Logger.MessageType.Tracking);
                request.Proxy = new WebProxy(ProxyServer, ProxyPort);
                CredentialCache c = new CredentialCache
                                        {{new Uri(url), "Basic", new NetworkCredential(ProxyUsername, ProxyPassword)}};
                request.Credentials = c;
            }
            return request;
        }

        #endregion

        #region EventHandlers

        #endregion
    }
}